package cn.xyy.system.dao;

import java.util.List;

import cn.xyy.jdbc.BaseDao;
import org.springframework.stereotype.Repository;

import cn.xyy.common.domain.mvc.Page;
import cn.xyy.common.domain.system.auth.DictItem;
import cn.xyy.common.domain.system.auth.DictItemVO;
import cn.xyy.common.utils.StringUtils;

/**
 * 字典数据持久层
 * 
 * @author xyy
 *
 */
@Repository
public class DictItemDao extends BaseDao {

	public Page<DictItem> selectPage(DictItemVO vo) {
		List<DictItem> list = super.select(
				getSqlPageHandle().handlerPagingSQL(pageSql(vo, 0), vo.getPage(), vo.getLimit()), null, DictItem.class);
		int count = super.getJdbcTemplate().queryForObject(pageSql(vo, 1), null, Integer.class);
		Page<DictItem> page = new Page<DictItem>(list, count, vo.getLimit(), vo.getPage());
		return page;
	}

	private String pageSql(DictItemVO vo, int type) {
		StringBuilder sql = new StringBuilder();
		if (type == 0) {
			sql.append(
					"select i.item_id as id,i.dict_id as dictId,d.dict_name as dictName,i.item_label as itemLabel,i.item_value as itemValue,i.sorts,i.status from t_sys_dict_item i");
			sql.append(" inner join  t_sys_dict d on i.dict_id=d.dict_id ");
		} else {
			sql.append("select count(*) from t_sys_dict_item i");
			sql.append(" inner join  t_sys_dict d on i.dict_id=d.dict_id ");
		}
		sql.append(" where 1=1");

		if (StringUtils.isNotBlank(vo.getItemLabel())) {
			sql.append(" and item_label like '%").append(vo.getItemLabel() + "%' ");
		}
		if (StringUtils.isNotBlank(vo.getItemValue())) {
			sql.append(" and item_value like '%").append(vo.getItemValue() + "%' ");
		}
		if (vo.getDictId() != null && !"0".equals(vo.getDictId())) {
			sql.append(" and d.dict_id =").append(vo.getDictId());
		}
		if (type == 0) {
			if (StringUtils.isNotBlank(vo.getSidx())) {
				if ((vo.getSord().trim().equalsIgnoreCase("asc"))) {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " asc");
				} else {
					sql.append(" order by " + vo.getSidx().split(" ")[0] + " desc");
				}
			} else {
				sql.append(" order by item_id desc");
			}
		}
		return sql.toString();
	}

	public List<DictItem> select(String dictName) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				"select i.item_label as itemLabel,i.item_value as itemValue,i.sorts,i.status from t_sys_dict_item i");
		sql.append(" inner join  t_sys_dict d on i.dict_id=d.dict_id ");
		sql.append(" where d.status=1 and  d.dict_name=? ");

		return super.select(sql.toString(), new Object[] { dictName }, DictItem.class);
	}

}
